package cn.net.scp.test.app;

public class CheckListHasLoop {

    public static void main(String[] args) {

    }


    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return null;
        }
        ListNode slow = pHead;
        ListNode fast = pHead;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next.next;
        }
        slow = pHead;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

// python implementation
/*

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def detectCycle(head: ListNode) -> ListNode:
    if not head or not head.next:
        return None  # 链表为空或只有一个节点，不可能有环

    slow = head
    fast = head

    # 快慢指针找到相遇点
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            break

    # 如果没有相遇点，说明没有环
    if not fast or not fast.next:
        return None

    # 找到环的入口
    slow = head
    while slow != fast:
        slow = slow.next
        fast = fast.next

    return slow  # 返回环的入口节点

 */
